package com.zj.study.subscribere;

import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Service;

/**
 * @author 赵赳
 * @since: 2021/8/6 9:07
 * @desc: 业务场景：订单过期取消订单 原理：redis 键空间机制 即 pub/sub 发布订阅模式
 */
@Log4j2
@Service
public class RedisSubscriber extends KeyExpirationEventMessageListener {

  private final static String SUB_EVENT_ORDER = "expired_order";


  public RedisSubscriber(RedisMessageListenerContainer listenerContainer) {
    super(listenerContainer);
  }

  /**
   * 接收过期key
   *
   * @param message 消息
   * @param pattern pattern
   */
  @Override
  public void onMessage(Message message, byte[] pattern) {
    String expiredKey = message.toString();
    var s = new String(message.getBody());
    System.out.println("s = " + s);
    if (expiredKey.contains(SUB_EVENT_ORDER)) {
      // ...
      var str = expiredKey.replace("expired_order:", "");
      var orderNo = Long.parseLong(str);
      log.info("监听到过期订单号，orderNo = 【{}】  ", orderNo);
      // 业务处理 ...
      log.info("业务处理过期订单");
    } else {
      // ...
      log.info("非订单业务信息");
    }
  }

}
